package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.wms.entity.WmsMaterialDetail;
import org.jeecg.modules.wms.mapper.WmsMaterialDetailMapper;
import org.jeecg.modules.wms.service.IWmsMaterialDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 物料组成明细服务实现类
 */
@Service
public class WmsMaterialDetailServiceImpl extends ServiceImpl<WmsMaterialDetailMapper, WmsMaterialDetail> implements IWmsMaterialDetailService {

    @Override
    public List<WmsMaterialDetail> listByMaterialId(String materialId) {
        return baseMapper.selectByMaterialId(materialId);
    }

    @Override
    public boolean deleteByMaterialId(String materialId) {
        return baseMapper.deleteByMaterialId(materialId) >= 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveDetails(String materialId, List<WmsMaterialDetail> details) {
        // 先删除原有明细
        deleteByMaterialId(materialId);
        
        // 如果明细为空，直接返回成功
        if (details == null || details.isEmpty()) {
            return true;
        }
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser != null ? loginUser.getUsername() : "system";
        Date now = new Date();
        
        // 设置每条明细的基本信息
        for (WmsMaterialDetail detail : details) {
            // 设置物料ID
            detail.setMaterialId(materialId);
            
            // 设置创建/更新信息
            detail.setCreateBy(username);
            detail.setCreateTime(now);
            detail.setUpdateBy(username);
            detail.setUpdateTime(now);
        }
        
        // 批量保存明细
        return saveBatch(details);
    }
} 